package com.ruoyi.common.utils;



import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * Description: 线程池工具类
 * <p>
 */
public class ThreadExecutorUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadExecutorUtil.class);


    public static final int THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;
    public static final int MAX_IMUM_POOL_SIZE = 50;
    public static final int THREAD_BLOCK_QUEUE_SIZE = 1000;
    private static ExecutorService executor;

    public ThreadExecutorUtil() {
    }

    public static void runTask(Runnable runnable) {
        long t = System.currentTimeMillis();
        executor.execute(runnable);
        int count = 0;

        try {
            count = ((ThreadPoolExecutor)executor).getActiveCount();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        if (count > (THREAD_POOL_SIZE * 2/3) ) {
            LOGGER.info(runnable + " thread running total time(" + (System.currentTimeMillis() - t) + ")ms, busy thread over " + count + "/" + THREAD_POOL_SIZE);
        }

    }

    public static void stopTask() {
        executor.shutdown();
    }

    static {
        executor = new ThreadPoolExecutor(THREAD_POOL_SIZE, MAX_IMUM_POOL_SIZE, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue(THREAD_BLOCK_QUEUE_SIZE), new BasicThreadFactory.Builder()
                .namingPattern("doc-upload-pool-%d")
                .daemon(false)
                .build(),
                new ThreadPoolExecutor.CallerRunsPolicy()); // 使用调用者线程执行被拒绝的任务
    }
}